<?php

class Recharge extends La_Controller {
	function __construct() {
		parent::__construct();
		$this->load->model(array('Card_model', 'Order_model','User_card_model', 'User_model'));
		if (!$this->authorize->is_admin_logged_in()) {
			la_redirect("/admin/login", "请先登录");
		}
		$this->data['nav'] = 'recharge';
	}
	
	function index() {
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$data = $this->input->post("data");
			foreach ($data as $row) {
				if ($row['id'] && $row['count']) {
					$user_id = (int)$row['id']-100000;
					$user = $this->User_model->find_by_id($user_id);
					if (empty($user)) {
						continue;
					}
					$order_data = array('created_by' => $user_id, 'amount' => 10 * $row['count'], 'status'=>1,'pay_method'=>'cash',
										'pay_time' => date("Y-m-d H:i:s"),'created' => date("Y-m-d H:i:s"));
					$order_id = $this->Order_model->add($order_data);
					for($i = 0; $i < $row['count']; $i++) {
						$card_id = $this->Card_model->add();
						$this->Order_model->add_card_to_order($card_id, $order_id);
						$this->User_card_model->add($user_id, $card_id);
					}
				}
			}
			la_redirect("/console/recharge/records", "充值成功");
		} else {
			$this->load->view('admin/recharge', $this->data);
		}
	}	
	
	
	public function records() {
		$offset = intval($this->uri->segment(4));
		
		$orders_count = $this->Order_model->get_count_by_condition(" o.status = 1");
		$this->load->library('pager');
		$config['base_url'] = site_url("console/recharge/records/");
		$config['total_rows'] = $orders_count;
		$config['per_page'] = LA_PAGE_SIZE;
		$config['uri_segment'] = 4;
		$this->pager->initialize($config);
		$orders = $this->Order_model->find_by_condition("o.status = 1", $offset, $config['per_page']);
		$this->data['orders'] = $orders;
		$this->data['total'] = $orders_count;
		$this->data['pager'] =  $this->pager->create_links();
		$this->load->view('admin/recharge_record', $this->data);
	}
}